import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.print.PrinterException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 主窗口类
 */
class MainFrame extends JFrame {
    private JPanel shoppingListPanel; // 购物清单面板
    private JPanel paymentPanel;      // 支付面板
    private JPanel receiptPanel;      // 小票面板
    private JPanel historyPanel;      // 历史记录面板
    private JPanel memberPanel;       // 会员面板

    private ArrayList<Item> shoppingList;      // 购物清单
    private ArrayList<Receipt> receiptHistory; // 收银历史记录
    private HashMap<String, Member> members;   // 会员信息

    public MainFrame() {
        // 初始化窗口
        setTitle("超市收银系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化数据
        shoppingList = new ArrayList<>();
        receiptHistory = new ArrayList<>();
        members = new HashMap<>();

        // 初始化界面
        initUI();
    }

    /**
     * 初始化界面
     */
    private void initUI() {
        // 使用边界布局
        setLayout(new BorderLayout());

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();

        // 初始化各个面板
        initShoppingListPanel();
        initPaymentPanel();
        initReceiptPanel();
        initHistoryPanel();
        initMemberPanel();

        // 添加选项卡
        tabbedPane.addTab("购物清单", shoppingListPanel);
        tabbedPane.addTab("支付", paymentPanel);
        tabbedPane.addTab("小票", receiptPanel);
        tabbedPane.addTab("历史记录", historyPanel);
        tabbedPane.addTab("会员管理", memberPanel);

        // 添加到主窗口
        add(tabbedPane, BorderLayout.CENTER);
    }

    /**
     * 初始化购物清单面板
     */
    private void initShoppingListPanel() {
        shoppingListPanel = new JPanel(new BorderLayout());

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel(
                new Object[][] {},
                new String[] {"商品编号", "商品名称", "单价", "数量", "小计"}
        );
        JTable table = new JTable(model);

        // 添加商品输入区域
        JPanel inputPanel = new JPanel();
        JTextField codeField = new JTextField(10);
        JTextField nameField = new JTextField(10);
        JTextField priceField = new JTextField(10);
        JTextField quantityField = new JTextField(5);
        JButton addButton = new JButton("添加商品");

        inputPanel.add(new JLabel("编号:"));
        inputPanel.add(codeField);
        inputPanel.add(new JLabel("名称:"));
        inputPanel.add(nameField);
        inputPanel.add(new JLabel("单价:"));
        inputPanel.add(priceField);
        inputPanel.add(new JLabel("数量:"));
        inputPanel.add(quantityField);
        inputPanel.add(addButton);

        // 添加商品按钮事件
        addButton.addActionListener(e -> {
            String code = codeField.getText();
            String name = nameField.getText();
            double price = Double.parseDouble(priceField.getText());
            int quantity = Integer.parseInt(quantityField.getText());

            Item item = new Item(code, name, price, quantity);
            shoppingList.add(item);

            // 更新表格
            model.addRow(new Object[] {
                    code, name, price, quantity, price * quantity
            });

            // 清空输入框
            codeField.setText("");
            nameField.setText("");
            priceField.setText("");
            quantityField.setText("");
        });

        shoppingListPanel.add(inputPanel, BorderLayout.NORTH);
        shoppingListPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    }

    /**
     * 初始化支付面板
     */
    /**
     * 初始化支付面板 - 增加会员卡支付功能
     */
    private void initPaymentPanel() {

        paymentPanel = new JPanel(new BorderLayout());

        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel totalLabel = new JLabel("总金额: ¥0.00");
        JTextField memberField = new JTextField(10);
        JButton checkMemberButton = new JButton("查询会员");
        JLabel balanceLabel = new JLabel("会员余额: ¥0.00");

        topPanel.add(totalLabel);
        topPanel.add(new JLabel("会员卡号:"));
        topPanel.add(memberField);
        topPanel.add(checkMemberButton);
        topPanel.add(balanceLabel);

        JPanel centerPanel = new JPanel();
        JButton cashButton = new JButton("现金支付");
        JButton qrCodeButton = new JButton("扫码支付");
        JButton memberPayButton = new JButton("会员卡支付");

        centerPanel.add(cashButton);
        centerPanel.add(qrCodeButton);
        centerPanel.add(memberPayButton);

        // 查询会员按钮事件
        checkMemberButton.addActionListener(e -> {
            String cardNo = memberField.getText().trim();
            Member member = members.get(cardNo);
            if (member != null) {
                balanceLabel.setText(String.format("会员余额: ¥%.2f", member.getBalance()));
            } else {
                JOptionPane.showMessageDialog(this, "会员不存在!");
                balanceLabel.setText("会员余额: ¥0.00");
            }
        });

        // 会员卡支付按钮事件
        memberPayButton.addActionListener(e -> {
            if (shoppingList.isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "购物清单为空，请先添加商品！",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
            String cardNo = memberField.getText().trim();
            Member member = members.get(cardNo);
            if (member == null) {
                JOptionPane.showMessageDialog(this, "请先输入有效的会员卡号!");
                return;
            }

            double total = calculateTotal();
            if (member.getBalance() >= total) {
                member.deductBalance(total);
                JOptionPane.showMessageDialog(this, "支付成功!");
                generateReceipt("会员卡");
                updateMemberTable((DefaultTableModel) ((JTable) ((JScrollPane) memberPanel.getComponent(1)).getViewport().getView()).getModel());
                balanceLabel.setText(String.format("会员余额: ¥%.2f", member.getBalance()));
            } else {
                JOptionPane.showMessageDialog(this, "会员卡余额不足!");
            }
        });

        // 原有支付按钮事件
        cashButton.addActionListener(e -> handleCashPayment());
        qrCodeButton.addActionListener(e -> handleQRCodePayment());

        paymentPanel.add(topPanel, BorderLayout.NORTH);
        paymentPanel.add(centerPanel, BorderLayout.CENTER);
    }

//    private void initPaymentPanel() {
//        paymentPanel = new JPanel(new BorderLayout());
//
//        JPanel topPanel = new JPanel();
//        JLabel totalLabel = new JLabel("总金额: ¥0.00");
//        JTextField memberField = new JTextField(10);
//        JButton checkMemberButton = new JButton("查询会员");
//
//        topPanel.add(totalLabel);
//        topPanel.add(new JLabel("会员卡号:"));
//        topPanel.add(memberField);
//        topPanel.add(checkMemberButton);
//
//        JPanel centerPanel = new JPanel();
//        JButton cashButton = new JButton("现金支付");
//        JButton qrCodeButton = new JButton("扫码支付");
//
//        centerPanel.add(cashButton);
//        centerPanel.add(qrCodeButton);
//
//        // 支付按钮事件
//        cashButton.addActionListener(e -> handleCashPayment());
//        qrCodeButton.addActionListener(e -> handleQRCodePayment());
//
//        paymentPanel.add(topPanel, BorderLayout.NORTH);
//        paymentPanel.add(centerPanel, BorderLayout.CENTER);
//    }

    /**
     * 初始化小票面板
     */
    private void initReceiptPanel() {
        receiptPanel = new JPanel(new BorderLayout());

        JTextArea receiptArea = new JTextArea();
        receiptArea.setEditable(false);

        JButton printButton = new JButton("打印小票");
        printButton.addActionListener(e -> printReceipt());

        receiptPanel.add(new JScrollPane(receiptArea), BorderLayout.CENTER);
        receiptPanel.add(printButton, BorderLayout.SOUTH);
    }

    /**
     * 初始化历史记录面板
     */
    private void initHistoryPanel() {
        historyPanel = new JPanel(new BorderLayout());

        DefaultTableModel model = new DefaultTableModel(
                new Object[][] {},
                new String[] {"交易时间", "总金额", "支付方式"}
        );
        JTable table = new JTable(model);

        historyPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    }

    /**
     * 初始化会员管理面板
     */

    /**
     * 初始化会员管理面板
     */
    private void initMemberPanel() {
        memberPanel = new JPanel(new BorderLayout());

        // 添加会员信息输入区域
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField cardNoField = new JTextField(10);
        JTextField nameField = new JTextField(10);
        JTextField phoneField = new JTextField(10);
        JTextField balanceField = new JTextField(10);
        JButton addButton = new JButton("添加会员");
        JButton editButton = new JButton("修改信息");
        JButton deleteButton = new JButton("删除会员");
        JButton rechargeButton = new JButton("充值");

        inputPanel.add(new JLabel("卡号:"));
        inputPanel.add(cardNoField);
        inputPanel.add(new JLabel("姓名:"));
        inputPanel.add(nameField);
        inputPanel.add(new JLabel("电话:"));
        inputPanel.add(phoneField);
        inputPanel.add(new JLabel("初始余额:"));
        inputPanel.add(balanceField);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(rechargeButton);

        // 会员列表表格
        DefaultTableModel model = new DefaultTableModel(
                new Object[][] {},
                new String[] {"会员卡号", "姓名", "电话", "积分", "余额"}
        ) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable table = new JTable(model);

        // 添加会员
        addButton.addActionListener(e -> {
            try {
                String cardNo = cardNoField.getText().trim();
                String name = nameField.getText().trim();
                String phone = phoneField.getText().trim();
                double balance = Double.parseDouble(balanceField.getText().trim());

                if (cardNo.isEmpty() || name.isEmpty() || phone.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请填写完整信息!");
                    return;
                }

                if (members.containsKey(cardNo)) {
                    JOptionPane.showMessageDialog(this, "会员卡号已存在!");
                    return;
                }

                Member member = new Member(cardNo, name, phone, balance);
                members.put(cardNo, member);
                updateMemberTable(model);
                clearMemberFields(cardNoField, nameField, phoneField, balanceField);

                JOptionPane.showMessageDialog(this, "会员添加成功!");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的金额!");
            }
        });

        // 修改会员信息
        editButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请先选择要修改的会员!");
                return;
            }

            String cardNo = (String) table.getValueAt(selectedRow, 0);
            Member member = members.get(cardNo);
            if (member != null) {
                String newName = JOptionPane.showInputDialog(this, "请输入新的姓名:", member.getName());
                String newPhone = JOptionPane.showInputDialog(this, "请输入新的电话:", member.getPhone());

                if (newName != null && newPhone != null) {
                    member.setName(newName);
                    member.setPhone(newPhone);
                    updateMemberTable(model);
                    JOptionPane.showMessageDialog(this, "修改成功!");
                }
            }
        });

        // 删除会员
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请先选择要删除的会员!");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除该会员吗?", "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                String cardNo = (String) table.getValueAt(selectedRow, 0);
                members.remove(cardNo);
                updateMemberTable(model);
                JOptionPane.showMessageDialog(this, "删除成功!");
            }
        });

        // 会员充值
        rechargeButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请先选择要充值的会员!");
                return;
            }

            String cardNo = (String) table.getValueAt(selectedRow, 0);
            Member member = members.get(cardNo);
            if (member != null) {
                String input = JOptionPane.showInputDialog(this,
                        String.format("当前余额: ¥%.2f\n请输入充值金额:", member.getBalance()));

                if (input != null) {
                    try {
                        double amount = Double.parseDouble(input);
                        if (amount > 0) {
                            member.addBalance(amount);
                            updateMemberTable(model);
                            JOptionPane.showMessageDialog(this, "充值成功!");
                        } else {
                            JOptionPane.showMessageDialog(this, "请输入大于0的金额!");
                        }
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(this, "请输入有效的金额!");
                    }
                }
            }
        });

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(inputPanel, BorderLayout.NORTH);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);

        memberPanel.add(topPanel, BorderLayout.NORTH);
        memberPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    }

//    private void initMemberPanel() {
//        memberPanel = new JPanel(new BorderLayout());
//
//        JPanel inputPanel = new JPanel();
//        JTextField cardNoField = new JTextField(10);
//        JTextField nameField = new JTextField(10);
//        JTextField phoneField = new JTextField(10);
//        JButton addButton = new JButton("添加会员");
//
//        inputPanel.add(new JLabel("卡号:"));
//        inputPanel.add(cardNoField);
//        inputPanel.add(new JLabel("姓名:"));
//        inputPanel.add(nameField);
//        inputPanel.add(new JLabel("电话:"));
//        inputPanel.add(phoneField);
//        inputPanel.add(addButton);
//
//        // 会员列表
//        DefaultTableModel model = new DefaultTableModel(
//                new Object[][] {},
//                new String[] {"会员卡号", "姓名", "电话", "积分"}
//        );
//        JTable table = new JTable(model);
//
//        memberPanel.add(inputPanel, BorderLayout.NORTH);
//        memberPanel.add(new JScrollPane(table), BorderLayout.CENTER);
//    }

    /**
     * 处理现金支付
     */
    private void handleCashPayment() {
        // 检查购物清单是否为空
        if (shoppingList.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "购物清单为空，请先添加商品！",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        double total = calculateTotal();
        String input = JOptionPane.showInputDialog(String.format("应付金额：¥%.2f\n请输入收到的现金金额:", total));
        if (input != null) {
            try {
                double received = Double.parseDouble(input);
                if (received >= total) {
                    double change = received - total;
                    JOptionPane.showMessageDialog(this,
                            String.format("找零: ¥%.2f", change));
                    generateReceipt("现金");
                } else {
                    JOptionPane.showMessageDialog(this,
                            "收到的现金不足!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this,
                        "请输入有效的金额!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 处理扫码支付
     */
    private void handleQRCodePayment() {
        // 检查购物清单是否为空
        if (shoppingList.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "购物清单为空，请先添加商品！",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 创建自定义对话框
        JDialog dialog = new JDialog(this, "扫码支付", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(300, 200);
        dialog.setLocationRelativeTo(this);

        // 添加提示信息
        JLabel msgLabel = new JLabel("请扫描二维码完成支付", JLabel.CENTER);
        msgLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

        // 显示应付金额
        double total = calculateTotal();
        JLabel amountLabel = new JLabel(String.format("应付金额：¥%.2f", total), JLabel.CENTER);

        JPanel centerPanel = new JPanel(new GridLayout(2, 1));
        centerPanel.add(msgLabel);
        centerPanel.add(amountLabel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton cancelButton = new JButton("取消");
        JButton confirmButton = new JButton("确认付款");

        buttonPanel.add(cancelButton);
        buttonPanel.add(confirmButton);

        // 添加按钮事件
        cancelButton.addActionListener(e -> {
            dialog.dispose();
            JOptionPane.showMessageDialog(this,
                    "支付已取消",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        });

        confirmButton.addActionListener(e -> {
            dialog.dispose();
            JOptionPane.showMessageDialog(this,
                    "支付成功！",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
            generateReceipt("扫码");
        });

        dialog.add(centerPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    /**
     * 生成小票
     */
    private void generateReceipt(String paymentMethod) {
        Receipt receipt = new Receipt(
                new Date(),
                shoppingList,
                calculateTotal(),
                paymentMethod
        );
        receiptHistory.add(receipt);

        // 更新小票显示
        JTextArea receiptArea = (JTextArea) ((JScrollPane) receiptPanel.getComponent(0)).getViewport().getView();
        receiptArea.setText(receipt.toString());

        // 更新历史记录
        updateHistoryPanel();

        // 清空购物清单
        shoppingList.clear();
        ((DefaultTableModel) ((JTable) ((JScrollPane) shoppingListPanel.getComponent(1)).getViewport().getView()).getModel()).setRowCount(0);
    }

    /**
     * 更新历史记录面板
     */
    private void updateHistoryPanel() {
        DefaultTableModel model = (DefaultTableModel) ((JTable) ((JScrollPane) historyPanel.getComponent(0)).getViewport().getView()).getModel();
        model.setRowCount(0); // 清空现有数据

        // 添加所有历史记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Receipt receipt : receiptHistory) {
            model.addRow(new Object[] {
                    sdf.format(receipt.getTimestamp()),
                    String.format("¥%.2f", receipt.getTotal()),
                    receipt.getPaymentMethod(),
                    receipt.getMemberNo() != null ? receipt.getMemberNo() : "非会员"
            });
        }
    }

    /**
     * 打印小票
     */
    private void printReceipt() {
        JTextArea receiptArea = (JTextArea) ((JScrollPane) receiptPanel.getComponent(0)).getViewport().getView();
        try {
            receiptArea.print();
        } catch (PrinterException e) {
            JOptionPane.showMessageDialog(this,
                    "打印失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 计算总金额
     */
    private double calculateTotal() {
        return shoppingList.stream()
                .mapToDouble(item -> item.getPrice() * item.getQuantity())
                .sum();
    }

    /**
     * 更新会员表格
     */
    private void updateMemberTable(DefaultTableModel model) {
        model.setRowCount(0);
        for (Member member : members.values()) {
            model.addRow(new Object[] {
                    member.getCardNo(),
                    member.getName(),
                    member.getPhone(),
                    member.getPoints(),
                    String.format("¥%.2f", member.getBalance())
            });
        }
    }

    /**
     * 清空会员信息输入框
     */
    private void clearMemberFields(JTextField... fields) {
        for (JTextField field : fields) {
            field.setText("");
        }
    }
}
